from fastapi import APIRouter, Depends, Request, Form, Query, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from sqlalchemy.orm import Session
from typing import Optional
from pydantic import BaseModel
from ..models import get_db, LinkCategory, Link, User, WebsiteConfig
from ..auth import get_current_user
from ..utils import paginate_query
import os
from fastapi.templating import Jinja2Templates

# 可以移除不需要的ToggleStatusRequest模型，因为我们不需要请求体

router = APIRouter()

# 获取模板目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))

# 链接分类列表页面
@router.get("/link-categories", response_class=HTMLResponse)
async def admin_link_categories(
    request: Request, 
    page: int = Query(1, ge=1), 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    query = db.query(LinkCategory)
    pagination = paginate_query(query, page, 20)
    
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="gradient")
    
    return templates.TemplateResponse("admin/link-categories.html", {
        "request": request, 
        "categories": pagination["items"],
        "current_page": pagination["current_page"],
        "total_pages": pagination["total_pages"],
        "total_items": pagination["total_items"],
        "page_size": pagination["page_size"],
        "current_user": current_user,
        "config": config
    })

# 添加链接分类页面
@router.get("/link-categories/add", response_class=HTMLResponse)
async def admin_add_link_category(
    request: Request, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/link-category-form.html", 
        {"request": request, "action": "add", "current_user": current_user, "config": config}
    )

# 编辑链接分类页面
@router.get("/link-categories/edit/{category_id}", response_class=HTMLResponse)
async def admin_edit_link_category(
    request: Request, 
    category_id: int, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    category = db.query(LinkCategory).filter(LinkCategory.id == category_id).first()
    if not category:
        raise HTTPException(status_code=404, detail="分类不存在")
    # 检查是否为内置分类
    if category.is_builtin:
        raise HTTPException(status_code=403, detail="内置分类不可编辑")
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/link-category-form.html", 
        {"request": request, "category": category, "action": "edit", "current_user": current_user, "config": config}
    )

# 保存链接分类
@router.post("/link-categories/save")
async def save_link_category(
    request: Request,
    id: Optional[int] = Form(None),
    name: str = Form(...),
    is_active: bool = Form(True),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # 检查分类名称是否已存在
    existing_category = db.query(LinkCategory).filter(LinkCategory.name == name).first()
    if existing_category and (id is None or existing_category.id != id):
        if id:
            category = db.query(LinkCategory).filter(LinkCategory.id == id).first()
            return templates.TemplateResponse(
                "admin/link-category-form.html", 
                {"request": request, "category": category, "action": "edit", "error": "分类名称已存在", "current_user": current_user}
            )
        else:
            return templates.TemplateResponse(
                "admin/link-category-form.html", 
                {"request": request, "action": "add", "error": "分类名称已存在", "current_user": current_user}
            )
    
    if id:
        category = db.query(LinkCategory).filter(LinkCategory.id == id).first()
        if category:
            category.name = name
            category.status = is_active
    else:
        category = LinkCategory(name=name, status=is_active)
        db.add(category)
    db.commit()
    return RedirectResponse(url="/admin/link-categories", status_code=302)

# 删除链接分类
@router.post("/link-categories/delete/{category_id}")
async def delete_link_category(
    category_id: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    category = db.query(LinkCategory).filter(LinkCategory.id == category_id).first()
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if not category:
        if is_ajax:
            return {"success": False, "message": "分类不存在"}
        else:
            raise HTTPException(status_code=404, detail="分类不存在")
    
    # 检查是否为内置分类
    if category.is_builtin:
        if is_ajax:
            return {"success": False, "message": "内置分类不可删除"}
        else:
            # 添加错误消息并重定向
            return templates.TemplateResponse(
                "admin/link-categories.html", 
                {
                    "request": request, 
                    "categories": db.query(LinkCategory).all(), 
                    "error": "内置分类不可删除", 
                    "current_user": current_user
                }
            )
    
    # 将该分类下的链接的category_id设为None
    db.query(Link).filter(Link.category_id == category_id).update({"category_id": None})
    db.delete(category)
    db.commit()
    
    if is_ajax:
        return {"success": True, "message": "删除成功"}
    else:
        return RedirectResponse(url="/admin/link-categories?message=删除成功", status_code=302)

# 批量删除链接分类
@router.post("/link-categories/batch-delete")
async def batch_delete_link_categories(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    form_data = await request.form()
    category_ids = form_data.getlist("category_ids")
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if not category_ids:
        if is_ajax:
            return {"success": False, "message": "请选择要删除的分类"}
        else:
            return RedirectResponse(url="/admin/link-categories?message=请选择要删除的分类", status_code=302)
    
    # 将字符串ID列表转换为整数列表
    category_ids = [int(id) for id in category_ids]
    # 查询选中的分类，排除内置分类
    categories = db.query(LinkCategory).filter(LinkCategory.id.in_(category_ids)).all()
    deletable_ids = [cat.id for cat in categories if not cat.is_builtin]
    
    if deletable_ids:
        # 将这些分类下的链接的category_id设为None
        db.query(Link).filter(Link.category_id.in_(deletable_ids)).update({"category_id": None})
        # 批量删除选中的可删除分类
        db.query(LinkCategory).filter(LinkCategory.id.in_(deletable_ids)).delete(synchronize_session=False)
        db.commit()
        
        if is_ajax:
            return {"success": True, "message": "批量删除成功"}
        else:
            return RedirectResponse(url="/admin/link-categories?message=批量删除成功", status_code=302)
    else:
        if is_ajax:
            return {"success": False, "message": "选中的分类均为内置分类，无法删除"}
        else:
            return RedirectResponse(url="/admin/link-categories?message=选中的分类均为内置分类，无法删除", status_code=302)

# 切换链接分类状态
@router.post("/link-categories/toggle-status/{category_id}")
async def toggle_category_status(
    category_id: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        # 查找链接分类
        category = db.query(LinkCategory).filter(LinkCategory.id == category_id).first()
        
        if not category:
            return {"success": False, "message": "分类不存在"}
        
        # 检查是否为内置分类
        if category.is_builtin:
            return {"success": False, "message": "内置分类不可禁用"}
        
        # 更新状态（取反当前状态）
        category.status = not category.status
        db.commit()
        
        status_text = "启用" if category.status else "禁用"
        return {"success": True, "message": f"分类{status_text}成功", "new_status": category.status}
    except Exception as e:
        db.rollback()
        return {"success": False, "message": f"状态切换失败: {str(e)}"}